package cn.com.shaom.learning.sb.security.example3;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;

/**
 * ClassName: CustomPermissionEvaluator
 * Description: 自定义的 PermissionEvaluator
 * Date: 2017/12/28 10:23 【需求编号】
 *
 * @author Shaom
 * @version V1.0.0
 */
@Component
public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Resource
    RefreshAuthenticationTools refreshAuthenticationTools;

    private final Logger logger = LoggerFactory.getLogger(CustomPermissionEvaluator.class);

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        if ((authentication == null) || (targetDomainObject == null) || !(permission instanceof String)) {
            return false;
        }
        return hasPrivilege(authentication, (String) targetDomainObject, permission.toString().toUpperCase());
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        if ((authentication == null) || (targetType == null) || !(permission instanceof String)) {
            return false;
        }
        return hasPrivilege(authentication, targetType.toUpperCase(), permission.toString().toUpperCase());
    }

    /**
     * 真正处理逻辑的地方
     *
     * @param auth
     * @param targetType
     * @param permission
     * @return
     */
    private boolean hasPrivilege(Authentication auth, String targetType, String permission) {
        logger.debug("~~~~~~~~~~~~~~~~~~~~~ 路径 ~~~~~~~~~~~~~~~~" + targetType);
        logger.debug("##################### 权限 ################" + permission);
        refreshAuthenticationTools.refresh();
        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        for (GrantedAuthority grantedAuth : authorities) {
            String authority = grantedAuth.getAuthority();
            if (authority.equalsIgnoreCase(permission)) {
                return true;
            }
        }
        return false;
    }
}
